<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="theme-color" content="#000000" />
    <meta
      name="description"
      content="Web site created using create-react-app"
    />
   
    <title>React App</title>
  </head>
  <body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>
   

   <div>
      
      <button onclick="store.dispatch({type:'JIAN', n:4})">-</button>
      <span id="countDisplay"></span>
      <button onclick="store.dispatch({type:'JIA', n:2})">+</button>
    </div>
    <script>
      
    
      function changeState(state, action) {
        if(!state) return countState;
          switch (action.type){
            case 'JIAN':
              return {
                ...state,
                count: state.count-action.n
              }
              break;
            case 'JIA':
            return {
                ...state,
                count: state.count+action.n
              }
              break;
            default:
              break;
            }

      }

      // 创建一个数据仓库,changeState相当于reducer
      function createStore(changeState) {
        let state = null;
        const getState = () => state
        // 第一次初始化的时候定义一个空数组，用于存放订阅的任务，当每次有新的任务订阅的时候押入栈中
        const listeners = []
        const subscrib = (listener) => {listeners.push(listener)}
        const dispatch = (action) => {
          state = changeState(state, action)
          listeners.forEach(listener => listener())
        }
        dispatch({})
        return {
          getState,
          dispatch,
          subscrib
        }
      }
      // 由于返回的是一个对象，只要被引用，里面的数据就不会被垃圾回收机制回收，所以实现数据保存
      const store = createStore(changeState)
      const renderCount = () => {
        countDisplay.innerHTML = store.getState().count
      }
      renderCount()

      store.subscrib(renderCount)
 

    </script>
  </body>
</html>
